package com.guoguo.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by li on 2017/5/3.
 */
public class FileUtils {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FileUtils.class);


    /**
     * 删除文件夹下的所有文件
     *
     * @param path
     */
    public static void removeFilePath(String path) {
        if (isExist(path)) {
            File file = new File(path);

            File[] fa = file.listFiles();
            for (int i = 0; i < fa.length; i++) {
                File fs = fa[i];
                if (fs.isDirectory()) {
                    logger.info("===========>>>>>>  [目录] ： " + fs.getName());
                    removeFilePath(fs.getPath());
                } else {
                    logger.info("===========>>>>>>  [删除文件] ： " + fs.getName());
                    fs.delete();
                }
            }
        } else {
            logger.info("============>>>>>>>  [错误的路径]： " + path);
        }
    }

    /**
     * 判断一个文件是否存在
     *
     * @param path 文件路径
     * @return 存在返回true，否则返回false
     */
    public static boolean isExist(String path) {
        try {
            return new File(path).exists();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * <pre>
     * 判断一个绝对路径下，是否有这个文件。如果没有，则会创建完整路径，并且创建这个文件。
     * </pre>
     *
     * @param path 文件的绝对路径
     */
    public static void createFile(String path) {
        File file = new File(path);
        if (!isExist(path)) {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Spring mvc 框架下文件上传
     *
     * @param request request
     * @param isZip   1:压缩；0：不压缩
     * @return
     */
    public static List<String> springFileUpload(HttpServletRequest request, int isZip) {
        long startTime = System.currentTimeMillis();
        List<String> fileList = new ArrayList<String>();

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            List<MultipartFile> multipartFiles = multiRequest.getFiles("fileName");
            for (MultipartFile multipartFile : multipartFiles) {
                if (multipartFile != null) {
                    logger.info("==============>>>>>  upload file:   " + multipartFile.getOriginalFilename());
                    String path = PropertyUtils.getProperty("aliyun.properties", "ali.localUrl") + multipartFile.getOriginalFilename();
                    String new_path = PropertyUtils.getProperty("aliyun.properties", "ali.localUrl.temp") + multipartFile.getOriginalFilename();
                    try {
                        createFile(path);
                        //上传文件到本地
                        multipartFile.transferTo(new File(path));
                        //1:压缩；0：不压缩
                        if (isZip == 1) {
                            ImageUtils.zipImage(path, new_path, 0, 0, 0.8f);
                            fileList.add(new_path);
                        } else {
                            fileList.add(path);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }
        }
        long endTime = System.currentTimeMillis();
        logger.info("==============>>>>>  文件上传花费时间：" + String.valueOf(endTime - startTime) + "ms");
        return fileList;
    }
}
